package com.gxar.quick.ar.server.base.common.utils;

import org.springframework.util.StopWatch;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

/**
 * 分享码工具
 *
 * @author linsy
 */
public class ShareCodeUtils {

    public static String[] CHARS = new String[]{"a", "b", "c", "d", "e", "f",
            "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
            "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    public static String generateShortUuid() {
        StringBuilder shortBuffer = new StringBuilder();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(CHARS[x % 0x3E]);
        }
        return shortBuffer.toString();
    }

    /**
     * 根据时间戳随机生成兑换码
     * @param length 生成长度
     * @return 响应
     */
    public static String generateNumber(Integer length) {
        // 获取当前时间戳
        long timestamp = System.currentTimeMillis();

        // 使用时间戳作为随机数种子
        Random random = new Random(timestamp);

        // 生成六位数字
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Set<String> codes = new HashSet<>();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        for (int i = 0; i < 20; i++) {
            String uuid = generateNumber(6);
            try {
                Thread.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(uuid);
            codes.add(uuid);
        }
        stopWatch.stop();
        System.out.println(codes.size());
        System.out.println(stopWatch.prettyPrint());
    }

}